<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/5/15
 * Time: 16:06
 */

namespace backend\controllers;


use common\controllers\BackendCommonCtrl;
use common\services\PersonnelClassSve;
use Yii;
use common\library\comFun;
use yii\helpers\Url;

class PersonnelClassController extends BackendCommonCtrl
{
    /**
     * 分类列表
     * @return string
     */
    public function actionList()
    {
        $PersonnelClassSve = new PersonnelClassSve();
        $rs = $PersonnelClassSve->getList([], 'sort DESC,personnel_class_id ASC', true);
        return $this->render('list',['list'=>comFun::formatTree($rs,'personnel_class_id')]);
    }

    /**
     * 添加分类
     * @return string
     */
    public function actionAdd()
    {
		//获取二级分类
        $PersonnelClassSve = new PersonnelClassSve();
        $rs = $PersonnelClassSve->getList([], 'sort DESC,personnel_class_id ASC', true);
        return $this->render('edit', ['list' => comFun::formatTree($rs,'personnel_class_id'),'info'=>[]]);
    }

    /**
     * 编辑分类
     * @return string|\yii\web\Response
     */
    public function actionEdit()
    {
        $request = Yii::$app->request;
        $PersonnelClassSve = new PersonnelClassSve();
        if ($request->isPost) {
            $data = $request->post();
            if($request->post('parent_id') == 0){
                unset($data['parent_id']);
            }
            if ($request->post('personnel_class_id')) {
                $rs = $PersonnelClassSve->update($data );
            } else {
                $rs = $PersonnelClassSve->add($data );
            }
            if ($rs['code'] === 0) {
                $rs['redirect'] = Url::toRoute('/personnel-class/list');
            }
            return $this->asJson($rs);
        } else {
            $id = $request->get('personnel_class_id');
            $data = ['Obj' => []];
            //检查id
            if (comFun::isPositiveInt($id)) {
                $rs = $PersonnelClassSve->getInfo(['personnel_class_id' => $id]);
                if ($rs['code'] === 0) {
                    $data = $rs['data'];
                }
            }
            //获取二级分类
            $PersonnelClassSve = new PersonnelClassSve();
            $rs = $PersonnelClassSve->getList([], 'sort DESC,personnel_class_id ASC', true);
            return $this->render('edit', ['info' => $data['Obj'],'list'=>comFun::formatTree($rs,'personnel_class_id')]);
        }
    }

    /**
     * 移除
     * @return array
     */
    public function actionRemove()
    {
        $personnelClassId = Yii::$app->request->get('personnel_class_id');
        $PersonnelClassSve = new PersonnelClassSve();
        $rs = $PersonnelClassSve->remove(['personnel_class_id' => $personnelClassId]);
        return $this->asJson($rs);
    }
}